<script setup lang="ts">
import { getQuestionInfo, getLatestQuestions, checkSqlContent } from '@/api/subject';
import type { Choice, Question } from '@/api/subject/type';
import YHeader from '@/components/YHeader.vue';
import { onMounted, ref, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import ChoiceAnswer from './components/ChoiceAnswer.vue';
import JudgeAnswer from './components/JudgeAnswer.vue';
import EssayAnswer from './components/EssayAnswer.vue';
import { getAnalysis } from '@/api/code/codeCompletion';
import MarkdownRenderer from '@/views/home/code/components/MarkdownRenderer.vue';
import { useUserStore } from '@/store/user';

const route = useRoute();
const router = useRouter();

const subjectId = ref('');
const question = ref({} as Question);
const answer = ref<string | string[]>([]);  
const choice = ref({} as Choice);
const title = ref('');
const isFinish = ref(false);
const isRight = ref(false);
const analysis = ref('AI思考中...');
const questionIdList = ref<string[]>([]);
const currentIndex = ref(0);


const toSubjectHome = () => {
  router.push({ name: 'SubjectHome', query: { id: route.query.subjectId } });
};
const fetchLatestQuestionIds = async () => {
  const subjectId = Array.isArray(route.query.subjectId)
    ? route.query.subjectId[0]
    : route.query.subjectId
  if (!subjectId) {
    console.error('未获取到 subjectId');
    return;
  }
  try {
    const res = await getLatestQuestions(subjectId);
    const questions = res.data && Array.isArray(res.data) ? res.data : res;
    if (!Array.isArray(questions)) {
      console.error('返回数据格式错误，不是数组：', questions);
      return;
    }
    questionIdList.value = questions.map((q: any) => q.id.toString());
    const currentIdRaw = Array.isArray(route.query.id)
      ? route.query.id[0]
      : route.query.id;
    currentIndex.value = questionIdList.value.findIndex(id => id === currentIdRaw);
    console.log('题目 ID 列表：', questionIdList.value, '当前索引：', currentIndex.value);
  } catch (error) {
    console.error('获取题目列表失败', error);
  }
};

const fetchQuestionInfo = async (id: string) => {
  try {
    const res = await getQuestionInfo(id);
    question.value = res.data;
    // 重置答题状态
    answer.value = question.value.type === "Choice" && question.value.answer.includes(",") ? [] : '';  // 初始化答案
    isFinish.value = false;
    analysis.value = 'AI思考中...';
    if (question.value.type === "Choice") {
      choice.value = JSON.parse(question.value.answer);
      title.value = choice.value.isMultiple ? '多选题' : '单选题';
    } else if (question.value.type === "Judge") {
      title.value = '判断题';
      try {
        const parsedAnswer = JSON.parse(question.value.answer);
        question.value.answer = parsedAnswer.correctAnswer === "true" ? "正确" : "错误";
      } catch (error) {
        console.error('Judge答案解析失败', error);
      }
    } else {
      title.value = '简答题';
    }
  } catch (error) {
    console.error('获取题目信息失败', error);
  }
};

onMounted(async () => {
  console.log('完整的 route 对象：', route);
  await fetchLatestQuestionIds();
  const currentId = Array.isArray(route.query.id)
    ? route.query.id[0] as string
    : route.query.id as string;
  if (currentId) {
    await fetchQuestionInfo(currentId);
  }
  subjectId.value = Array.isArray(route.query.subjectId)
    ? route.query.subjectId[0] as string
    : route.query.subjectId as string;
});

watch(currentIndex, async () => {
  const currentId = questionIdList.value[currentIndex.value];
  if (currentId) {
    answer.value = question.value.type === "Choice" && question.value.answer.includes(",") ? [] : ''; // 清空答案
    await fetchQuestionInfo(currentId); 
  }
});

const goLast = async () => {
  if (currentIndex.value > 0) {
    currentIndex.value--; 
    const lastId = questionIdList.value[currentIndex.value]; 
    router.push({ name: route.name as string, query: { subjectId: route.query.subjectId, id: lastId } });
  }
};

const goNext = () => {
  if (currentIndex.value < questionIdList.value.length - 1) {
    currentIndex.value++; 
    const nextId = questionIdList.value[currentIndex.value];
    router.push({ name: route.name as string, query: { subjectId: route.query.subjectId, id: nextId } });
  }
};

const submitAnswer = async () => {
  isFinish.value = true;
  if (question.value.type === 'Choice') {
    if (choice.value.isMultiple) {
      const userAnswerSet = new Set(answer.value as string[]); 
      const correctAnswerSet = new Set(
        choice.value.correctAnswer.map((index: number) => choice.value.options[index])  // 正确答案的选项值
      );
      isRight.value = userAnswerSet.size === correctAnswerSet.size && [...userAnswerSet].every(option => correctAnswerSet.has(option));
    } else {
      isRight.value = answer.value === choice.value.options[choice.value.correctAnswer];
    }
  } else if (question.value.type === 'Judge') {
    const userAnswer = answer.value === 'true' ? '正确' : answer.value === 'false' ? '错误' : answer.value;
    isRight.value = userAnswer === question.value.answer;
  } else if (question.value.type === 'Essay') {
    const userStore = useUserStore();
    const userId = userStore.getId;
    if (!Array.isArray(answer.value)) {
      checkSqlContent(subjectId.value, question.value.id, userId, answer.value);
    }
  }
  try {
    console.log('用户答案', answer.value, '题目标题', question.value.title);
    analysis.value = await getAnalysis(question.value.title, answer.value);
  } catch (error) {
    analysis.value = 'AI解析失败';
  }
};
</script>

<template>
  <div class="container">
    <YHeader :name="'答题'"></YHeader>
    <!-- <div class="container-icon">
        <div class="icon">
            <van-icon @click="toSubjectHome" name="arrow-left" size="32" />
        </div>
        <div class="center">
            <p style="margin: 0%; font-size: 15px;">答题</p>
        </div>
    </div> -->
    <div class="content" v-if="question">
      <div class="question-info">
        <div class="type">
          <van-tag type="primary">{{ title }}</van-tag>
        </div>
        <div class="title">
          {{ question.title }}
        </div>
      </div>
      <div class="answer-area">
        <template v-if="question.type === 'Choice'">
          <ChoiceAnswer v-model="answer" :choice="choice" />
        </template>
        <template v-else-if="question.type === 'Judge'">
          <JudgeAnswer v-model="answer" />
        </template>
        <template v-else>
          <EssayAnswer v-model="answer" />
        </template>
      </div>
      <!-- <div class="answer-result" v-if="isFinish">
        <div v-if="isRight">
          <van-tag type="success">回答正确</van-tag>
          <h4>你的答案</h4>
          <template v-if="question.type === 'Judge'">
            {{ answer === 'true' ? '正确' : answer === 'false' ? '错误' : answer }}
          </template>
          <template v-else-if="question.type === 'Choice'">
            <template v-if="choice.isMultiple">
            {{ Array.isArray(answer) ? answer.join(', ') : answer }}
            </template>
            <template v-else>
              {{ answer }}
            </template>
          </template>
          <template v-else>
            {{ answer }}
          </template>
        </div>
        <div v-else>
          <van-tag type="danger">回答错误</van-tag>
          <h4>你的答案</h4>
          <template v-if="question.type === 'Judge'">
            {{ answer === 'true' ? '正确' : answer === 'false' ? '错误' : answer }}
          </template>
          <template v-if="choice.isMultiple">
              {{ Array.isArray(answer) ? answer.join(', ') : answer }}
            </template>
          <template v-else>
            {{ answer }}
          </template>
        </div>
        <div>
          <h4>正确答案</h4>
          <template v-if="question.type === 'Choice'">
            <template v-if="choice.isMultiple">
              <div v-for="(opt, index) in choice.correctAnswer" :key="index">
                {{ choice.options[opt] }}
              </div>
            </template>
            <template v-else>
              {{ choice.options[choice.correctAnswer] }}
            </template>
          </template>
          <template v-else>
            {{ question.answer }}
          </template>
        </div>
        <div>
          <h4>AI解析</h4>
          <MarkdownRenderer style="width: 100%; line-height: 1.6;" :content="analysis" />
        </div>
      </div> -->
      <div class="bottom-bar">
        <van-button type="primary" block v-if="!isFinish" @click="submitAnswer">提交答案</van-button>
        <div>
          <van-button  @click="goLast" :disabled="currentIndex === 0">上一题</van-button>
          <van-button  @click="goNext" :disabled="currentIndex === questionIdList.length - 1">下一题</van-button>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.container {
  width: 100%;
  height: 100%;
  background-color: #f7f8fa;
}
.content {
  padding: 16px;
}
.question-info {
  background-color: #fff;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 16px;
  .type {
    margin-bottom: 8px;
  }
  .title {
    font-size: 16px;
    font-weight: 500;
    line-height: 1.5;
  }
}
.answer-area {
  margin-bottom: 16px;
}
.answer-result {
  background-color: #fff;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 16px;
}
.bottom-bar {
  position: fixed;
  bottom: 16px;
  left: 16px;
  right: 16px;
  display: flex;
  flex-direction: column;
  gap: 8px;
}
.container-icon {
    display: flex;
    background-color: white;
    flex-basis: 50px;
    flex-direction: row;
    align-items: center;
    border-bottom: 1px rgba(0, 0, 0, 0.13) solid;
    width: 100%;
    position: relative; /* 为子元素的绝对定位提供参考 */
    .icon {
        position: absolute; /* 绝对定位 */
        left: 16px; /* 距离左侧 16px */
        display: flex;
        align-items: center;
    }
    .center {
        display: flex;
        width: 100%;
        justify-content: center;
        align-items: center;
    }
}
</style>
